package com.cuit.controller;

import com.cuit.doamin.Department;
import com.cuit.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/depart")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    @RequestMapping("/add")
    public ModelAndView add(Integer did, String dname) {
        ModelAndView mv = new ModelAndView();
        Department d = new Department();
        d.setD_id(did);
        d.setD_name(dname);

        boolean b = departmentService.add(d);
        if (b) {
            mv.setViewName("pages/success");
        } else {
            mv.setViewName("pages/error");
        }
        return mv;
    }

    @RequestMapping("/update")
    public ModelAndView update(Integer did, String dname) {
        ModelAndView mv = new ModelAndView();
        Department d = new Department();
        d.setD_id(did);
        d.setD_name(dname);

        boolean b = departmentService.update(d);
        if (b) {
            mv.setViewName("pages/success");
        } else {
            mv.setViewName("pages/error");
        }
        return mv;
    }

    @RequestMapping("/delete")
    public ModelAndView delete(String depart, String type) {
        ModelAndView mv = new ModelAndView();
        Department d = new Department();

        if (type.equals("id")) {
            Integer id = Integer.valueOf(depart);
            d.setD_id(id);
        } else {
            d.setD_name(depart);
        }

        boolean b = departmentService.delete(d);

        if (b) {
            mv.setViewName("pages/success");
        } else {
            mv.setViewName("pages/error");
        }
        return mv;
    }

    @RequestMapping("/find")
    public ModelAndView find() {
        ModelAndView mv = new ModelAndView();

        List<Department> list = departmentService.findAll();

        if (list.size() > 0) {
            mv.addObject("list", list);
            mv.setViewName("admin/find_department");
        } else {
            mv.setViewName("pages/error");
        }
        return mv;
    }
}
